package com.tpl.core.basedata.service.sys.impl;


import java.util.Calendar;
import java.util.Date;

import com.tpl.core.basedata.common.task.TaskUtil;
import com.tpl.core.basedata.dao.TriggerTaskDao;
import com.tpl.core.basedata.service.sys.TriggerTaskService;
import com.tpl.core.common.exception.RuleException;
import com.tpl.core.common.page.Page;
import com.tpl.core.dao.ExecuteSql;
import com.tpl.core.entity.sys.TriggerTask;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;



/**
 * 说明 :
 * @author <a href="mailto:3380084@gmail.com">张坤雷</a>
 * @version 创建时间：2013-8-2 上午11:07:47 
 *
 */
public class TriggerTaskServiceImpl implements TriggerTaskService {
	@Autowired
    TriggerTaskDao triggerTaskDao;
	@Override
	public Page getTaskPage(int pageIndex, int pageSize) {
//		List<TriggerTask> list=triggerTaskDao.getTaskList(pageIndex,pageSize);
		Page page=triggerTaskDao.getTaskPage(pageIndex, pageSize);
//		Page page=new ListPage(list, pageIndex, pageSize, count);
		return page;
	}

	@Override
	public TriggerTask getTaskById(long id) {
		return triggerTaskDao.getTaskById(id);
	}

	@Override
	public void doSave(TriggerTask task) {
		if(task.getId()==null){
			task.setCreateDate(task.getUpdateDate());
			task.setCreator(task.getUpdator());
			triggerTaskDao.insert(task);
		}else
			triggerTaskDao.update(task);
	}

	@Override
	public void doChangeState(long id, int state) {
		TriggerTask task=triggerTaskDao.getTaskById(id);
		if(task.getState()==state)
			throw new RuleException("此任务已经是"+(state>0?"上线":"下线")+"状态,不需要重复操作.");
		triggerTaskDao.doChangeState(state, id);
	}

	@Override
	public void doDelete(long id) {
		triggerTaskDao.delete(id);
	}

	@Override
	public void changeCronExp(TriggerTask task) {
		if(task.getState()==1){
			String cronExp=task.getCronExpression();
			String [] cronArray=cronExp.split(" ");
			int second=Integer.valueOf(cronArray[0])+Integer.valueOf(cronArray[1])*60+Integer.valueOf(cronArray[2])*3600;
			Date curDate=Calendar.getInstance().getTime();
			int  curSecond=curDate.getHours()*3600+curDate.getMinutes()*60+curDate.getSeconds();
			if(Math.abs(second-curSecond)<300){
				throw new RuleException("该定时任务在5分钟内执行,如要修改,请先下线或5分钟后再操作.");
			}
		}
		String sql="update BD_TRIGGER_TASK set cron_expression=? where id=?";
		ExecuteSql.execute(sql, task.getCronExpression(),task.getId());
		
	}
	@Override
	public void doWriteLog(Long id, int state, String info) {
		info=StringUtils.isNotEmpty(info)&&info.length()>200?info.substring(0,200):info;
		String curDate= DateTime.now().toString("yyyy-MM-dd HH:mm:ss");
        TriggerTask task=triggerTaskDao.getTaskById(id);
        triggerTaskDao.afterExcute(id,curDate);
        if(task.getType()==0)
        	TaskUtil.stopTask(id);
    	ExecuteSql.execute("Insert Into bd_trigger_task_log(execute_date,state,task_key,remark) Values(?,?,?,?)", curDate,state,task.getTaskKey(),info);
	}


}
